#' ---
#' title: "Whose Dimension is it anyway: Graphs and Tables"
#' author: "Lukas F. Stoetzer"
#' ---

#' Script estimates irt models for Senator Representation Study


  # Libraries 
    library(tidyverse)
    library(gridExtra)
    library(reshape2)
    
  # Utiltiy Functions
    source("utilits.R")


## 0) Load Results ==============
  
  # Load Results
    load("res_cces08_scaling.Rdata")
    load("res_cces10_scaling.Rdata")
    load("res_cces12_scaling.Rdata")
    
  # Prepare Item Names
    cces_08_items <- data.frame(
      study="CCES08",item=1:9,
      short=c("TrpsIrq", "MnmWg", "StmCll",
              "FISA","Schip","GaMrrg",
              "Hsng", "NAFTA", "Bank")) 
    
    cces_10_items <- data.frame(
      study="CCES10",item=1:9,
      short=c("RcvryRnvst", "Schip", "ClnEnrgy",
              "HlthRfrm","FinRef","EdAdT",
              "FISA", "StmCll", "Bank")) 
    
    cces_12_items <- data.frame(
      study="CCES12",item=c(1:9),
      short=c("RyanBud", "SimpBoyles", 
              "TaxCut",
              "BrthCntrl","TrdKorea","RplHlth",
              "Pplne", "Hlth", "EdAdT")) 
    
  # Load Results
    load("res_srs_scaling.Rdata")
    
  # Prepare Item Names
    srs_items <- data.frame(
      study="SRS",item=1:27, 
      type = c("Hard item", "Item" , "Hard item", "Hard item","Item",
               "Easy item","Item","Item","Item","Hard item","Hard item","Easy item",
               "Hard item","Item","Item","Item",
               "Easy item","Easy item","Easy item","Easy item",
               "Item","Item","Easy item","Item","Easy item",
               "Hard item","Hard item"),
      short = c("BsnStr","NclWr","CETA","Bnk","GntanmBy","FmlsTx","ChlsCr","RdsFrst","ChldSf",
                "StpPrvt Fdrl Jbs","MltaBs","MnmWg","PrtcAms","CgaTx","MrcEm","FmlPla","RseInTx2","RseInTx",
                "UnbrnVctms","HtCrm","FlEcn",
                "GsRdc","BaTrtMltry","Armr","NatWld","PyRfl","FrnAct"),
      desc = c("Jumpstart Our Business Strength Act","Remove Funding for Bunker Buster Nuclear Warhead",
               "Central American Free Trade Agreement","Bankruptcy Abuse Prevention and Consumer Protection Act",
               "Remove Funding for Guantanamo Bay Detention Center",
               "Working Families Tax Relief Act",  "Child Care Funding for Welfare Recipients",
               "Prohibiting Roads in Tongass National Forest", "Child Safety Locks Amendment",
               "Stopping Privatization of Federal Jobs", "Military Base Closure Delays",
               "Minimum Wage Increase", "Protection of Lawful Commerce in Arms Act",
               "Cigarette Tax Increase", "Disapproval of Mercury Emissions Rule",
               "Family Planning Aid Policy (Mexico City Policy)", "Raise Tax Rate on Income over One Million Dollars",
               "Raise Tax Rate on Highest Income Bracket" , "Unborn Victims of Violence Act",
               "Federal Hate Crimes","Fuel Economy Standards",
               "Greenhouse Gas Reduction and Credit Trading System", "Banning Torture by U.S. Military Interrogators",
               "Broaden Definition of Armor Piercing Ammunition", "Prohibit Drilling in Arctic National Wildlife Refuge",
               "Overtime Pay Regulations",   "Class Action Fairness Act")
    )  
    
  # Cbmn 
    items <- bind_rows(cces_08_items,
                       cces_10_items,
                       cces_12_items,
                       srs_items)
    
## 1) Estimated Discrimination Paramter ============
  
  # Bind Gamma Estimates in List
    rls <- list(leg_08,  resp_08,
                leg_10,  resp_10,
                leg_12,  resp_12,
                leg_srs, resp_srs
                )
    
  # Function to get alpha and beta estimates
    df_item <- do.call("rbind",lapply(1:length(rls),function(i) data.frame("item"=1:dim(rls[[i]]$beta)[2],
                                                                           "beta"=apply((rls[[i]]$beta[,,1]),2,median),
                                                                           "alpha"=apply((rls[[i]]$beta[,,2]),2,median),
                                                                           "case"=i)))
    
  # Create Data.frame
    df_item$case <- as.character(factor(df_item$case, 
                                        labels = c("CCES08_leg","CCES08_resp",#"CCES08_respind","CCES08_resppid",
                                                    "CCES10_leg","CCES10_resp",#"CCES10_respind","CCES10_resppid",
                                                   "CCES12_leg","CCES12_resp", 
                                                   "SRS_leg","SRS_resp"
                                                    )))
  # Respahe
    df_item <- tidyr::separate(df_item,"case",c("study","type")) %>%
      gather(cat,val,alpha,beta) %>%
      spread(type,val) 

  # Add Item Inoramtion
    df_items_par <- left_join(df_item,items)
  
  # Add Description for some items 
    df_items_par <- mutate(df_items_par, 
                           sel_desc = as.factor(case_when(
                             study == "CCES08" & item %in% c(1) ~ "dark",
                             study == "CCES10" & item %in% c(4) ~ "dark",
                             study == "CCES12" & item %in% c(3) ~ "dark",
                             study == "SRS" & item %in% c(19) ~ "dark",
                             TRUE ~ "light")))
  # Make a plot
    lim <- 1.3*max(abs(filter(df_items_par,cat=="beta")$leg))
    df_items_beta <- filter(df_items_par,cat=="beta")  
  
    filter(df_items_par, study %in% c("CCES10","CCES12"), cat=="beta") %>%
      arrange(short)
    
  # Plot 
    ggplot() +
    geom_point(data=df_items_beta,aes(x=leg,y=resp, col= sel_desc)) +
    geom_text(data=filter(df_items_beta, sel_desc == "dark"), 
              aes(x=leg,y=resp, label=short),
              nudge_x = -.5, nudge_y = -1.5) +
    theme_minimal() + #theme(aspect.ratio = 1) +
    scale_color_grey(start = 0, end = 0.8) +
    facet_wrap(~ study, ncol = 2) +
    ylim(c(-lim,lim)) + xlim(c(-lim,lim)) +
    geom_abline(a=0,b=1,col="grey",alpha=0.4) + 
    geom_hline(yintercept = 0,col="grey",alpha=0.4) + 
    geom_vline(xintercept =0,col="grey",alpha=0.4)  +
    theme(panel.grid.minor = element_blank(),
          panel.background = element_rect("grey98",linetype = "blank"), legend.position = "None")  +
    ylab("Respondent Discrimination") + xlab("Senator Discrimination")
  

  ggsave("fig_alpha_scatter.pdf", width = 6,height = 6, dpi=300)
  

## 2) Estimated Difficulty Paramter ============
  
  # Make a plot
  lim <- 1.3*max(abs(filter(df_items_par,cat=="alpha")$leg))
  df_items_alpha <- filter(df_items_par,cat=="alpha")  
  df_items_alpha <- df_items_alpha %>% 
    gather(type, val, leg, resp) %>%
    mutate(type = case_when(type == "resp" ~ "Respondent Scaling",
                            type == "leg"  ~ "Senator Scaling"))
  
  # Plot 
  ggplot() +
    geom_boxplot(data=df_items_alpha, 
                 aes(y=val, x=type, fill=type),alpha=0.6, outlier.shape = NA) +
    geom_jitter(data=df_items_alpha, 
                 aes(y=val, x=type, fill=type),position=position_jitter(0.1)) +
    coord_flip() + 
    theme_minimal() + 
    facet_wrap(~ study, ncol = 2)  +
    scale_fill_grey() +
    theme(panel.background = element_rect("grey98",linetype = "blank"), legend.position = "None")  +
    ylab("Difficulty Paramter") + xlab("")
  
  
  ggsave("fig_alpha_boxplot.pdf", width = 6,height = 4,dpi=300)
  